<template>
  <div>
    <h1>聊天室</h1>
<!--    1.进入聊天室-->
    <div>
      <van-field
          v-model="name"
          center
          clearable
          label="昵称"
          placeholder="请输入昵称"
      >
        <template #button>
          <van-button size="small" @click="connectServer" type="primary">连接</van-button>
        </template>
      </van-field>
    </div>
<!--    2.聊天区-->
    <div>
      <van-cell v-for="(m,index) in msgs" :title="m" :key="index"/>
    </div>
<!--    3.发布聊天内容-->
    <div>
      <van-field
          v-model="msg"
          center
          clearable
          label="内容"
          placeholder="请输入聊天内容"
      >
        <template #button>
          <van-button size="small" @click="sendMsg" type="primary">发送</van-button>
        </template>
      </van-field>
    </div>
  </div>
</template>
<script>
var ws;
export default {
  data(){
    return{
      name:"",
      msg:"",
      msgs:[]
    }
  },
  mounted() {

  },
  methods:{
    connectServer(){
      //连接服务器
      ws = new WebSocket("ws://localhost:8888/ws/chat/"+this.name);
      ws.onopen =()=>{this.$toast("亲，欢迎加入")};
      ws.onmessage=(evt)=>{this.loadData(evt.data)}
    },
    sendMsg(){
      //发送消息
      ws.send(this.msg);
    },
    loadData(m){
      console.log(m);
      //接收消息
      this.msgs.push(m);
    }
  }
}
</script>